package com.sky.flyweight;

import java.util.HashMap;

/**
 * 非享元角色
 */
class OperationObj {

    private String opName;  //name 作为唯一标识

    OperationObj(String opName) {
        this.opName = opName;
    }

    public String getOpName() {
        return opName;
    }

    public void setOpName(String opName) {
        this.opName = opName;
    }


}


/**
 * 抽象 享元角色
 */
interface FlyWeight {

    void operate(OperationObj operationObj);
}


/**
 * 具体享元角色
 */
class ConcreteFlyWeight implements FlyWeight {

    private String FlyWeightName;


    ConcreteFlyWeight(String FlyWeightName) {
        this.FlyWeightName = FlyWeightName;
    }

    @Override
    public void operate(OperationObj operationObj) {
        System.out.print(" DEBUG  具体享元对象" + this.FlyWeightName + "被调用，它的地址是: " + this.toString() + "; ");
        System.out.println("   现在正在执行: " + operationObj.getOpName());
    }
}

/**
 * 享元工厂角色
 */
class FlyWeightFactory {

    private HashMap<String, FlyWeight> flyWeightHashMap = new HashMap<>();

    /**
     * 获取 or  创建 享元对象
     */
    FlyWeight getFlyWeight(String name) {
        FlyWeight flyWeight = flyWeightHashMap.get(name);
        if (flyWeight != null) {
            System.out.println(" WARN  具体享元对象:" + name + "已经存在, 不会再次创建！");
        } else {
            System.out.println(" INFO 创建享元对象: " + name);
            flyWeight = new ConcreteFlyWeight(name);
            flyWeightHashMap.put(name, flyWeight);
        }
        return flyWeight;
    }


}


/**
 * @author : wushikai
 * <p>
 * date : 2020-08-12
 */
public class Application {


    public static void main(String[] args) {
        FlyWeightFactory factory = new FlyWeightFactory();
        FlyWeight flyWeightA01 = factory.getFlyWeight("flyWeightA");
        FlyWeight flyWeightA02 = factory.getFlyWeight("flyWeightA");
        FlyWeight flyWeightA03 = factory.getFlyWeight("flyWeightA");
        FlyWeight flyWeightB01 = factory.getFlyWeight("flyWeightB");
        FlyWeight flyWeightB02 = factory.getFlyWeight("flyWeightB");

        flyWeightA01.operate(new OperationObj("学尼玛;"));
        flyWeightA02.operate(new OperationObj("学泥唠唠"));
        flyWeightA03.operate(new OperationObj("学泥大爷"));

        System.out.println("  WARN  flyWeightA01.equals(flyWeightA02) = " + flyWeightA01.equals(flyWeightA02));


        flyWeightB01.operate(new OperationObj("学泥梅梅"));
        flyWeightB02.operate(new OperationObj("学泥设计模式"));
    }


}

